const {
	Service
} = require("uni-cloud-router");
const {
	result_success,
	result_error
} = require('http-result-modle')
/* const {
	get_out_trade_no_wmz
} = require('common-uuid') */
const {
	ADVER_LIST_PLATFORM_WX
} = require('config-wmz-adver')

const db = uniCloud.database()
const dbCmd = db.command
const table_adverShopConfig = "wmz-adver-shop-config"
const table_adversingWechat = "wmz-adver-wechat-info"
const table_appletInfo = "wmz-applet-info"
const table_cateringShop = "catering-shop"

module.exports = class WmzAdverCateringServcice extends(
	Service
) {
	async wxAdverInit(shopId, appId, adunitList) {
		let adverList = ADVER_LIST_PLATFORM_WX
		let dbDelete, dbAdd, advertising = {}
		if(!adunitList){
			adunitList = await this.advertisingAdunitInitWxService(appId, shopId)
			if(adunitList.code === 200 && adunitList.data.length > 0){
				adunitList = adunitList.data
			} else {
				return result_error("微信广告adunitId获取失败！")
			}
		}
		for(let i = 0, len = adunitList.length; i < len; i++){
			advertising[adunitList[i].adversing_type] = adunitList[i]
		}
		if (adverList && adverList.length > 0) {
			for (let i = 0, len = adverList.length; i < len; i++) {
				adverList[i].app_id = appId
				adverList[i].shop_id = shopId
				adverList[i].adver_code = get_out_trade_no_wmz()
				adverList[i].create_time = new Date().getTime()
				switch (adverList[i].adver_type){
					case 'wx_custom':
						if(advertising.SLOT_ID_WEAPP_TEMPLATE && advertising.SLOT_ID_WEAPP_TEMPLATE.ad_unit_id){
							adverList[i].adver_id = advertising.SLOT_ID_WEAPP_TEMPLATE.ad_unit_id
							adverList[i].adversing_type = advertising.SLOT_ID_WEAPP_TEMPLATE.adversing_type
						}
						break
					case 'wx_video':
						if(advertising.SLOT_ID_WEAPP_VIDEO_FEEDS && advertising.SLOT_ID_WEAPP_VIDEO_FEEDS.ad_unit_id){
							adverList[i].adver_id = advertising.SLOT_ID_WEAPP_VIDEO_FEEDS.ad_unit_id
							adverList[i].adversing_type = advertising.SLOT_ID_WEAPP_TEMPLATE.adversing_type
						}
						break
					case 'wx_interstitial':
						if(advertising.SLOT_ID_WEAPP_INTERSTITIAL && advertising.SLOT_ID_WEAPP_INTERSTITIAL.ad_unit_id){
							adverList[i].adver_id = advertising.SLOT_ID_WEAPP_INTERSTITIAL.ad_unit_id
							adverList[i].adversing_type = advertising.SLOT_ID_WEAPP_TEMPLATE.adversing_type
						}
						break
					case 'wx_banner':
						if(advertising.SLOT_ID_WEAPP_BANNER && advertising.SLOT_ID_WEAPP_BANNER.ad_unit_id){
							adverList[i].adver_id = advertising.SLOT_ID_WEAPP_BANNER.ad_unit_id
							adverList[i].adversing_type = advertising.SLOT_ID_WEAPP_TEMPLATE.adversing_type
						}
						break
				}
			}
			uniCloud.logger.log("adverList********")
			uniCloud.logger.log(adverList)
			dbDelete = await db.collection(table_adverShopConfig).where({
				app_id: appId,
				shop_id: shopId,
				ad_provider: "wx",
				project_code: "wmz_catering"
			}).remove()
			dbAdd = await db.collection(table_adverShopConfig).add(adverList)
			return result_success()
		} else {
			return result_error("获取平台广告列表异常！")
		}
		return result_error("未知异常！")
	}

	async adverShopConfigGet(projectCode, adProvider, shopId, appId) {
		// shopId='807102f6623f02d10200df5f520a15a0'
		let where = {
			project_code: projectCode,
			ad_provider: adProvider,
			shop_id: shopId
		}
		if(!shopId || !appId){
			return result_error("没有获取到商户的appId和shopId！")
		}
		let adverConfig = await db.collection(table_adverShopConfig).where(where).field({
			adver_code: true,
			adver_id: true,
			is_enable: true,
			space_code: true,
			name: true,
			adversing_type: true
		}).get()
		let adverConfigObj = {
			
		}
		if(adverConfig && adverConfig.data && adverConfig.data.length > 0){
			adverConfig = adverConfig.data
			for(let i = 0, len = adverConfig.length; i < len; i++){
				adverConfigObj[adverConfig[i].space_code] = adverConfig[i]
			}
			return result_success(adverConfigObj)
		}
		return result_error("没有获取到广告信息！")
	}

	async advertisingCheckCanOpenWxService(appId) {
		let reqRes, dbUpdate;
		let dbApletInfo = await mainDb.collection(table_appletInfo).where({
			_id: appId
		}).field({
			"wechat_id": true,
			"wechat_advertising_can_open": true,
			"wechat_advertising_open": true,
			"wechat_advertising_open_errer": true
		}).get()
		if(dbApletInfo && dbApletInfo.data && dbApletInfo.data.length > 0){
			dbApletInfo = dbApletInfo.data[0]
			if(dbApletInfo.wechat_advertising_can_open){
				return result_success(dbApletInfo.wechat_advertising_can_open)
			}
			reqRes = await uniCloud.callFunction({
				name: "wechat",
				data: {
					path: "/advertising/operationamsCheckOpenPublisher",
					data: {
						appId: appId
					}
				}
			})
			reqRes = reqRes.result
			if(reqRes.code === 200 && parseInt(reqRes.data.status) === 1){
				dbUpdate = await mainDb.collection(table_appletInfo).where({
					_id: appId
				}).update({
					wechat_advertising_can_open: true
				})
				return result_success(true)
			} else {
				dbUpdate = await mainDb.collection(table_appletInfo).where({
					_id: appId
				}).update({
					wechat_advertising_can_open: false,
					wechat_advertising_open_errer: reqRes.data.err_msg
				})
				return result_error(reqRes.data.err_msg)
			}
		} else {
			return result_error("appId：" + appId + "异常， 没有对应的商户信息！")
		}
		return result_error("未知错误！")
	}

	/**
	 * 微信广告创建初始化
	 * @param appId
	 * @param shopId
	 * @returns {Promise<*>}
	 */
	async advertisingAdunitInitWxService(appId, shopId){
		if(!shopId || !appId){
			return result_error("没有获取到商户的appId或shopId！")
		}
		let dbData = await db.collection(table_adversingWechat).where({
			shop_id: shopId
		}).field({
			adversing_type: true,
			ad_unit_id: true
		}).get()
		let dbUpdate, advertising = {

		};
		let adunitInfo, reqRes, advertisingList = [];
		if(dbData && dbData.data && dbData.data.length > 0){
			advertisingList = dbData.data
			for(let i = 0, len = dbData.data.length; i < len; i++){
				advertising[dbData.data[i].adversing_type] = dbData.data[i]
			}
		}
		if(!advertising.SLOT_ID_WEAPP_BANNER || !advertising.SLOT_ID_WEAPP_BANNER.ad_unit_id){
			adunitInfo = {
				name: shopId + "banner广告",
				type: "SLOT_ID_WEAPP_BANNER"
			}
			reqRes = await this.advertisingAdunitCreateWxService(appId, shopId, adunitInfo, advertising.SLOT_ID_WEAPP_BANNER)
			if(reqRes.code === 200){
				advertisingList.push(reqRes.data)
			}
		}
		if(!advertising.SLOT_ID_WEAPP_REWARD_VIDEO || !advertising.SLOT_ID_WEAPP_REWARD_VIDEO.ad_unit_id){
			adunitInfo = {
				name: shopId + "激励视频广告",
				type: "SLOT_ID_WEAPP_REWARD_VIDEO",
				video_duration_min: 6,
				video_duration_max: 15
			}
			reqRes = await this.advertisingAdunitCreateWxService(appId, shopId, adunitInfo, advertising.SLOT_ID_WEAPP_REWARD_VIDEO)
			if(reqRes.code === 200){
				advertisingList.push(reqRes.data)
			}
		}
		if(!advertising.SLOT_ID_WEAPP_INTERSTITIAL || !advertising.SLOT_ID_WEAPP_INTERSTITIAL.ad_unit_id){
			adunitInfo = {
				name: shopId + "小程序插屏广告",
				type: "SLOT_ID_WEAPP_INTERSTITIAL"
			}
			reqRes = await this.advertisingAdunitCreateWxService(appId, shopId, adunitInfo, advertising.SLOT_ID_WEAPP_INTERSTITIAL)
			if(reqRes.code === 200){
				advertisingList.push(reqRes.data)
			}
		}
		if(!advertising.SLOT_ID_WEAPP_VIDEO_FEEDS || !advertising.SLOT_ID_WEAPP_VIDEO_FEEDS.ad_unit_id){
			adunitInfo = {
				name: shopId + "小程序视频广告",
				type: "SLOT_ID_WEAPP_VIDEO_FEEDS"
			}
			reqRes = await this.advertisingAdunitCreateWxService(appId, shopId, adunitInfo, advertising.SLOT_ID_WEAPP_VIDEO_FEEDS)
			if(reqRes.code === 200){
				advertisingList.push(reqRes.data)
			}
		}
		if(!advertising.SLOT_ID_WEAPP_VIDEO_BEGIN || !advertising.SLOT_ID_WEAPP_VIDEO_BEGIN.ad_unit_id){
			adunitInfo = {
				name: shopId + "小程序视频贴片广告",
				type: "SLOT_ID_WEAPP_VIDEO_BEGIN"
			}
			reqRes = await this.advertisingAdunitCreateWxService(appId, shopId, adunitInfo, advertising.SLOT_ID_WEAPP_VIDEO_BEGIN)
			if(reqRes.code === 200){
				advertisingList.push(reqRes.data)
			}
		}
		if(!advertising.SLOT_ID_WEAPP_COVER || !advertising.SLOT_ID_WEAPP_COVER.ad_unit_id){
			adunitInfo = {
				name: shopId + "小程序封面广告",
				type: "SLOT_ID_WEAPP_COVER"
			}
			reqRes = await this.advertisingAdunitCreateWxService(appId, shopId, adunitInfo, advertising.SLOT_ID_WEAPP_COVER)
			if(reqRes.code === 200){
				advertisingList.push(reqRes.data)
			}
		}
		if(!advertising.SLOT_ID_WEAPP_TEMPLATE || !advertising.SLOT_ID_WEAPP_TEMPLATE.ad_unit_id){
			adunitInfo = {
				name: shopId + "小程序模板广告",
				type: "SLOT_ID_WEAPP_TEMPLATE",
				tmpl_type: 11
			}
			reqRes = await this.advertisingAdunitCreateWxService(appId, shopId, adunitInfo, advertising.SLOT_ID_WEAPP_TEMPLATE)
			if(reqRes.code === 200){
				advertisingList.push(reqRes.data)
			}
		}
		dbUpdate = await mainDb.collection(table_appletInfo).where({
			_id: appId
		}).update({
			wechat_advertising_open: true,
			wechat_advertising_open_errer: "流量主开通成功！"
		})
		return result_success(advertisingList)
	}

	async advertisingAdunitCreateWxService(appId, shopId, adunitInfo, oldAdvertising){
		let docId, dbUpdate;
		if(oldAdvertising){
			docId = oldAdvertising._id
		}
		let dbData = {
			app_id: appId,
			shop_id: shopId,
			create_time: new Date().getTime(),
			adversing_name: adunitInfo.name,
			adversing_type: adunitInfo.type
		}
		if(adunitInfo.video_duration_min){
			dbData.video_duration_min = adunitInfo.video_duration_min
		}
		if(adunitInfo.video_duration_max){
			dbData.video_duration_max = adunitInfo.video_duration_max
		}
		if(adunitInfo.tmpl_type){
			dbData.tmpl_type = adunitInfo.tmpl_type
		}
		if(docId){
			dbUpdate = await db.collection(table_adversingWechat).doc(docId).update(dbData)
		}else{
			let dbAdd = await db.collection(table_adversingWechat).add(dbData)
			docId = dbAdd.id
		}

		let reqRes = await uniCloud.callFunction({
			name: "wechat",
			data: {
				path: "/advertising/operationamsCreateAdunit",
				data: {
					appId: appId,
					adunitInfo: adunitInfo
				}
			}
		})
		reqRes = reqRes.result

		if(reqRes.code === 200){
			dbUpdate = await db.collection(table_adversingWechat).doc(docId).update({
				ad_unit_id: reqRes.data.ad_unit_id,
				resp_code: reqRes.data.ret,
				resp_data: reqRes.data
			})
			dbData.ad_unit_id = reqRes.data.ad_unit_id
			dbData.resp_code = reqRes.data.ret
			dbData.resp_data = reqRes.data
			return result_success(dbData)
		} else {
			dbUpdate = await db.collection(table_adversingWechat).doc(docId).update({
				resp_code: reqRes.data.ret,
				resp_error: reqRes.data
			})
		}
		return result_error(reqRes.data.err_msg || reqRes.data.msg)
	}

	/**
	 * 广告定时任务
	 * @returns {Promise<*>}
	 */
	async timedTaskService(){
		let count =  await mainDb.collection(table_appletInfo).count()
		count = count.total
		let pageCount = count / 100 + 1
		let appletList, lastCreatedate, item, checkCanOpen, shopList, adunitInit, temporaryDb, runCount = 0;
		lastCreatedate = 0
		for(let i = 0; i <  pageCount; i++){
			appletList = await mainDb.collection(table_appletInfo).where({
				wechat_id: dbCmd.exists(true),
				wechat_version: dbCmd.exists(true),
				wechat_advertising_open:  dbCmd.exists(false).or(dbCmd.eq(false)),
				create_time: dbCmd.gt(lastCreatedate)
			}).field({
				wechat_id: true,
				wechat_advertising_can_open: true,
				wechat_advertising_open: true,
				space_id: true,
				create_time: true
			}).limit(100).get()
			lastCreatedate = appletList.data[appletList.data.length - 1].create_time
			if(appletList && appletList.data && appletList.data.length > 0){
				for(let j = 0, lenJ = appletList.data.length; j < lenJ; j++){
					item = appletList.data[j]
					if(!item.wechat_advertising_can_open){
						checkCanOpen = await this.advertisingCheckCanOpenWxService(item._id)
						if(checkCanOpen.code === 200){
							if(item.space_id){
								temporaryDb = uniCloud.database({
									provider: 'tencent',
									spaceId: item.space_id
								})
							} else {
								temporaryDb = mainDb
							}

							shopList = await temporaryDb.collection(table_cateringShop).where({
								app_id: item._id,
								status_code: dbCmd.exists(false).or(dbCmd.eq(1))
							}).field({
								business_flag: true
							})
							if(shopList && shopList.data && shopList.data.length > 0){
								for(let k = 0, lenk = shopList.data.length; k < lenk; k++){
									adunitInit = await this.advertisingAdunitInitWxService(item._id, shopList.data[k]._id)
									if(adunitInit.code === 200){
										runCount++;
										await this.wxAdverInit(item._id, shopList.data[k]._id, adunitInit.data)
									}
								}
							}
						}
					}
				}
			}
		}
		let rspData = {
			count: count,
			runCount: runCount
		}
		return result_success(rspData)
	}
};
